package system.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import com.google.common.collect.Maps;
import common.model.po.SysBusinessCode;
import common.model.po.SysBusinessCodeDetail;
import common.util.TreeUtil;

import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * 组装业务编码数据
 *
 * @author 米泽鹏
 */
public class BusinessCodeBuilder {

	private BusinessCodeBuilder() {
		throw new AssertionError("不可实例化");
	}

	public static TreeMap<String, List<Tree<Long>>> buildBusinessCodeData(List<SysBusinessCode> businessCodeList, List<SysBusinessCodeDetail> businessCodeDetailList) {
		TreeMap<String, List<Tree<Long>>> result = Maps.newTreeMap();
		for (SysBusinessCode sysBusinessCode2 : businessCodeList) {
			List<SysBusinessCodeDetail> detailList = businessCodeDetailList.stream().filter(sysBusinessCodeDetail -> sysBusinessCodeDetail.getBusinessCodeId().equals(sysBusinessCode2.getId())).collect(Collectors.toList());
			List<Tree<Long>> roots = buildBusinessCodeDetailData(detailList, true);
			result.put(sysBusinessCode2.getCodeType(), roots);
		}
		return result;
	}

	public static List<Tree<Long>> buildBusinessCodeDetailData(List<SysBusinessCodeDetail> businessCodeDetailList, boolean fullPathValue) {
		TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
		treeNodeConfig.setIdKey("id");
		treeNodeConfig.setParentIdKey("parentId");
		treeNodeConfig.setWeightKey("sort");
		treeNodeConfig.setNameKey("name");
		treeNodeConfig.setChildrenKey("children");
		List<Tree<Long>> roots = TreeUtil.build(businessCodeDetailList, 0L, treeNodeConfig, (businessCodeDetail, treeNode) -> {
			treeNode.setId(businessCodeDetail.getId());
			treeNode.setParentId(businessCodeDetail.getParentId());
			treeNode.setWeight(businessCodeDetail.getSort());
			treeNode.putExtra("value", businessCodeDetail.getValue());
			treeNode.putExtra("label", businessCodeDetail.getLabel());
		});
		if (fullPathValue) {
			// 递归设置父节点并拼接下级节点的value
			TreeUtil.treeIteratorDown(roots, treeNode -> {
				List<Tree<Long>> children = treeNode.getChildren();
				if (CollUtil.isNotEmpty(children)) {
					for (Tree<Long> child : children) {
						child.putExtra("value", treeNode.get("value") + "." + child.get("value"));
					}
				}
			}, Tree::getChildren);
		}
		return roots;
	}

}
